const api = require('../../../utils/api')

Page({
  data: {
    id: null,
    product: null,
    isCarousel: false,
    isRecommended: false,
    isHot: false,
    carouselSort: 0,
    recommendSort: 0
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadProduct(options.id)
    }
  },

  async loadProduct(id) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    })

    try {
      const res = await api.getProductDetail(id)
      if (res.success) {
        const product = res.data
        this.setData({
          product,
          isCarousel: product.isCarousel || false,
          isRecommended: product.isRecommended || false,
          isHot: product.isHot || false,
          carouselSort: product.carouselSort || 0,
          recommendSort: product.recommendSort || 0
        })
      } else {
        this.showError('加载失败')
      }
    } catch (error) {
      console.error('加载商品详情失败:', error)
      this.showError('加载失败')
    } finally {
      wx.hideLoading()
    }
  },

  onCarouselChange(e) {
    this.setData({
      isCarousel: e.detail.value
    })
  },

  onRecommendedChange(e) {
    this.setData({
      isRecommended: e.detail.value
    })
  },

  onHotChange(e) {
    this.setData({
      isHot: e.detail.value
    })
  },

  onCarouselSortInput(e) {
    this.setData({
      carouselSort: parseInt(e.detail.value) || 0
    })
  },

  onRecommendSortInput(e) {
    this.setData({
      recommendSort: parseInt(e.detail.value) || 0
    })
  },

  async handleSave() {
    const { id, isCarousel, isRecommended, isHot, carouselSort, recommendSort } = this.data

    wx.showLoading({
      title: '保存中...',
      mask: true
    })

    try {
      const res = await api.updateProductDisplay(id, {
        isCarousel,
        isRecommended,
        isHot,
        carouselSort,
        recommendSort
      })

      if (res.success) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              wx.navigateBack()
            }, 2000)
          }
        })
      } else {
        this.showError('保存失败')
      }
    } catch (error) {
      console.error('保存展示设置失败:', error)
      this.showError('保存失败')
    } finally {
      wx.hideLoading()
    }
  },

  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none'
    })
  }
}) 